import { Suspense, useEffect, useState } from "react";
import { useRoutes } from "react-router-dom";
import { useDispatch } from "react-redux";
import routes from "./routes";
import "./App.scss";
import LoadingPage from "./pages/loading";
import { configCache } from "./utils/configCache";
import { getToken } from "./utils";
import { loginAction } from "./store/user/loginUserSlice";
import { saveConfigAction, SystemConfigStoreInterface } from "./store/system/systemConfigSlice";
import { isMobile } from "./utils/index";

const App = () => {
  const dispatch = useDispatch();
  const [isInitialized, setIsInitialized] = useState(false);
  const [initError, setInitError] = useState<string | null>(null);
  const views = useRoutes(routes);

  useEffect(() => {
    const initializeApp = async () => {
      try {
        console.log("App: 开始初始化应用");
        
        // 获取系统配置
        const configRes = await configCache.getConfig();
        
        if (configRes?.data) {
          const config: SystemConfigStoreInterface = {
            //系统配置
            "ldap-enabled": configRes.data["ldap-enabled"],
            systemApiUrl: configRes.data["system-api-url"],
            systemH5Url: configRes.data["system-h5-url"],
            systemLogo: configRes.data["system-logo"],
            systemName: configRes.data["system-name"],
            systemPcUrl: configRes.data["system-pc-url"],
            pcIndexFooterMsg: configRes.data["system-pc-index-footer-msg"],
            //播放器配置
            playerPoster: configRes.data["player-poster"],
            playerIsEnabledBulletSecret:
              configRes.data["player-is-enabled-bullet-secret"] &&
              configRes.data["player-is-enabled-bullet-secret"] === "1"
                ? true
                : false,
            playerIsDisabledDrag:
              configRes.data["player-disabled-drag"] &&
              configRes.data["player-disabled-drag"] === "1"
                ? true
                : false,
            playerBulletSecretText: configRes.data["player-bullet-secret-text"],
            playerBulletSecretColor: configRes.data["player-bullet-secret-color"],
            playerBulletSecretOpacity: configRes.data["player-bullet-secret-opacity"],
          };
          dispatch(saveConfigAction(config));
          
          // 检查是否需要跳转到移动端
          if (isMobile() && configRes.data["system-h5-url"] !== "") {
            window.location.href = configRes.data["system-h5-url"];
            return;
          }
        }

        // 如果用户已登录，获取用户信息
        if (getToken()) {
          try {
            const userRes = await configCache.getUserInfo();
            if (userRes?.data) {
              dispatch(loginAction(userRes.data));
            }
          } catch (error) {
            console.warn("获取用户信息失败，但系统配置已加载:", error);
          }
        }

        console.log("App: 应用初始化完成");
        setIsInitialized(true);
      } catch (error) {
        console.error("App: 应用初始化失败:", error);
        setInitError("应用初始化失败，请刷新页面重试");
        setIsInitialized(true); // 即使失败也要渲染，避免白屏
      }
    };

    initializeApp();
  }, [dispatch]);

  if (!isInitialized) {
    return <LoadingPage />;
  }

  if (initError) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '100vh',
        flexDirection: 'column',
        gap: '20px'
      }}>
        <div style={{ color: 'red', fontSize: '16px' }}>{initError}</div>
        <button 
          onClick={() => window.location.reload()}
          style={{
            padding: '10px 20px',
            fontSize: '14px',
            cursor: 'pointer'
          }}
        >
          刷新页面
        </button>
      </div>
    );
  }

  return <Suspense fallback={<LoadingPage />}>{views}</Suspense>;
};

export default App;
